Use AutoAI and Lale to predict credit risk with ibm-watson-machine-learning¶

This notebook contains the steps and code to demonstrate support of AutoAI experiments in Watson Machine Learning service. It introduces commands for data retrieval, training experiments, persisting pipelines, testing pipelines, refining pipelines, and scoring.

Some familiarity with Python is helpful. This notebook uses Python 3.9.

Learning goals¶

The learning goals of this notebook are:

  • Work with Watson Machine Learning experiments to train AutoAI models.
  • Compare trained models quality and select the best one for further refinement.
  • Refine the best model and test new variations.
  • Online deployment and score the trained model.

Contents¶

This notebook contains the following parts:

  1. Setup
  2. Optimizer definition
  3. Experiment Run
  4. Pipelines comparison and testing
  5. Historical runs
  6. Pipeline refinement and testing
  7. Deploy and Score
  8. Cleanup
  9. Summary and next steps

1. Set up the environment¶

Before you use the sample code in this notebook, you must perform the following setup tasks:

  • Create a Watson Machine Learning (WML) Service instance (a free plan is offered and information about how to create the instance can be found here).
  • Create a Cloud Object Storage (COS) instance (a lite plan is offered and information about how to order storage can be found here).
    Note: When using Watson Studio, you already have a COS instance associated with the project you are running the notebook in.

Connection to WML¶

Authenticate the Watson Machine Learning service on IBM Cloud. You need to provide Cloud API key and location.

Tip: Your Cloud API key can be generated by going to the Users section of the Cloud console. From that page, click your name, scroll down to the API Keys section, and click Create an IBM Cloud API key. Give your key a name and click Create, then copy the created key and paste it below. You can also get a service specific url by going to the Endpoint URLs section of the Watson Machine Learning docs. You can check your instance location in your Watson Machine Learning (WML) Service instance details.

You can use IBM Cloud CLI to retrieve the instance location.

ibmcloud login --apikey API_KEY -a https://cloud.ibm.com
ibmcloud resource service-instance WML_INSTANCE_NAME

NOTE: You can also get a service specific apikey by going to the Service IDs section of the Cloud Console. From that page, click Create, and then copy the created key and paste it in the following cell.

Action: Enter your api_key and location in the following cell.

In [1]:
api_key = 'PUT_YOUR_KEY_HERE'
location = 'us-south'
In [2]:
wml_credentials = {
    "apikey": api_key,
    "url": 'https://' + location + '.ml.cloud.ibm.com'
}

Install and import the ibm-watson-machine-learning and dependecies¶

Note: ibm-watson-machine-learning documentation can be found here.

In [ ]:
!pip install -U ibm-watson-machine-learning | tail -n 1
!pip install -U autoai-libs | tail -n 1
!pip install -U scikit-learn==1.0.2 | tail -n 1
!pip install wget | tail -n 1
!pip install matplotlib | tail -n 1
In [47]:
from ibm_watson_machine_learning import APIClient

client = APIClient(wml_credentials)

Working with spaces¶

You need to create a space that will be used for your work. If you do not have a space, you can use Deployment Spaces Dashboard to create one.

  • Click New Deployment Space
  • Create an empty space
  • Select Cloud Object Storage
  • Select Watson Machine Learning instance and press Create
  • Copy space_id and paste it below

Tip: You can also use SDK to prepare the space for your work. More information can be found here.

Action: assign space ID below

In [4]:
space_id = 'PASTE YOUR SPACE ID HERE'

You can use the list method to print all existing spaces.

In [ ]:
client.spaces.list(limit=10)

To be able to interact with all resources available in Watson Machine Learning, you need to set the space which you will be using.

In [48]:
client.set.default_space(space_id)
Out[48]:
'SUCCESS'

Connections to COS¶

In next cell we read the COS credentials from the space.

In [5]:
cos_credentials = client.spaces.get_details(space_id=space_id)['entity']['storage']['properties']

2. Optimizer definition¶

Training data connection¶

Define connection information to COS bucket and training data CSV file. This example uses the German Credit Risk dataset.

The code in next cell uploads training data to the bucket.

In [6]:
filename = 'credit_risk_training_light.csv'
datasource_name = 'bluemixcloudobjectstorage'
bucketname = cos_credentials['bucket_name']

Download training data from git repository.

In [49]:
import os, wget

url = 'https://raw.githubusercontent.com/IBM/watson-machine-learning-samples/master/cloud/data/credit_risk/credit_risk_training_light.csv'
if not os.path.isfile(filename): wget.download(url)

Create connection¶

In [ ]:
conn_meta_props= {
    client.connections.ConfigurationMetaNames.NAME: f"Connection to Database - {datasource_name} ",
    client.connections.ConfigurationMetaNames.DATASOURCE_TYPE: client.connections.get_datasource_type_uid_by_name(datasource_name),
    client.connections.ConfigurationMetaNames.DESCRIPTION: "Connection to external Database",
    client.connections.ConfigurationMetaNames.PROPERTIES: {
        'bucket': bucketname,
        'access_key': cos_credentials['credentials']['editor']['access_key_id'],
        'secret_key': cos_credentials['credentials']['editor']['secret_access_key'],
        'iam_url': 'https://iam.cloud.ibm.com/identity/token',
        'url': cos_credentials['endpoint_url']
    }
}

conn_details = client.connections.create(meta_props=conn_meta_props)

Note: The above connection can be initialized alternatively with api_key and resource_instance_id.
The above cell can be replaced with:

conn_meta_props= {
    client.connections.ConfigurationMetaNames.NAME: f"Connection to Database - {db_name} ",
    client.connections.ConfigurationMetaNames.DATASOURCE_TYPE: client.connections.get_datasource_type_uid_by_name(db_name),
    client.connections.ConfigurationMetaNames.DESCRIPTION: "Connection to external Database",
    client.connections.ConfigurationMetaNames.PROPERTIES: {
        'bucket': bucket_name,
        'api_key': cos_credentials['apikey'],
        'resource_instance_id': cos_credentials['resource_instance_id'],
        'iam_url': 'https://iam.cloud.ibm.com/identity/token',
        'url': 'https://s3.us.cloud-object-storage.appdomain.cloud'
    }
}

conn_details = client.connections.create(meta_props=conn_meta_props)
In [ ]:
connection_id = client.connections.get_uid(conn_details)

Define connection information to training data.

In [50]:
from ibm_watson_machine_learning.helpers import DataConnection, S3Location


credit_risk_conn = DataConnection(
    connection_asset_id=connection_id,
    location=S3Location(bucket=bucketname,
                        path=filename))

training_data_reference=[credit_risk_conn]

Check the connection information. Upload the data and validate.

In [ ]:
credit_risk_conn.set_client(client)
credit_risk_conn.write(data=filename, remote_name=filename)
credit_risk_conn.read()

Optimizer configuration¶

Provide the input information for AutoAI optimizer:

  • name - experiment name
  • prediction_type - type of the problem
  • prediction_column - target column name
  • scoring - optimization metric
In [9]:
from ibm_watson_machine_learning.experiment import AutoAI

experiment = AutoAI(wml_credentials, space_id=space_id)

pipeline_optimizer = experiment.optimizer(
    name='Credit Risk Prediction - AutoAI',
    prediction_type=AutoAI.PredictionType.BINARY,
    prediction_column='Risk',
    scoring=AutoAI.Metrics.ROC_AUC_SCORE,
)

Configuration parameters can be retrieved via get_params().

In [10]:
pipeline_optimizer.get_params()
Out[10]:
{'name': 'Credit Risk Prediction - AutoAI',
 'desc': '',
 'prediction_type': 'binary',
 'prediction_column': 'Risk',
 'prediction_columns': None,
 'timestamp_column_name': None,
 'scoring': 'roc_auc',
 'holdout_size': 0.1,
 'max_num_daub_ensembles': 2,
 't_shirt_size': 'l',
 'train_sample_rows_test_size': None,
 'include_only_estimators': None,
 'backtest_num': None,
 'lookback_window': None,
 'forecast_window': None,
 'backtest_gap_length': None,
 'cognito_transform_names': None,
 'data_join_graph': False,
 'csv_separator': ',',
 'excel_sheet': 0,
 'encoding': 'utf-8',
 'positive_label': None,
 'drop_duplicates': True,
 'text_processing': None,
 'word2vec_feature_number': None,
 'daub_give_priority_to_runtime': None,
 'text_columns_names': None,
 'n_parallel_data_connections': None,
 'test_data_csv_separator': ',',
 'test_data_excel_sheet': 0,
 'test_data_encoding': 'utf-8',
 'categorical_imputation_strategy': None,
 'numerical_imputation_strategy': None,
 'numerical_imputation_value': None,
 'imputation_threshold': None,
 'retrain_on_holdout': True,
 'run_id': None}

3. Experiment run¶

Call the fit() method to trigger the AutoAI experiment. You can either use interactive mode (synchronous job) or background mode (asychronous job) by specifying background_model=True.

In [11]:
run_details = pipeline_optimizer.fit(
            training_data_reference=training_data_reference,
            background_mode=False)
Training job 7384eed1-8198-4e85-a1a7-35f5be7b5033 completed: 100%|████████| [04:05<00:00,  2.46s/it]

You can use the get_run_status() method to monitor AutoAI jobs in background mode.

In [12]:
pipeline_optimizer.get_run_status()
Out[12]:
'completed'

4. Pipelines comparison and testing¶

You can list trained pipelines and evaluation metrics information in the form of a Pandas DataFrame by calling the summary() method. You can use the DataFrame to compare all discovered pipelines and select the one you like for further testing.

In [13]:
summary = pipeline_optimizer.summary()
summary
Out[13]:
Enhancements Estimator training_roc_auc_(optimized) holdout_precision training_average_precision holdout_average_precision training_log_loss holdout_recall training_precision holdout_accuracy holdout_balanced_accuracy training_recall holdout_f1 holdout_log_loss training_accuracy holdout_roc_auc training_balanced_accuracy training_f1
Pipeline Name
Pipeline_4 HPO, FE LGBMClassifier 0.857847 0.846154 0.847072 0.547020 0.565612 0.647059 0.885287 0.68 0.698529 0.794872 0.733333 0.599960 0.785886 0.235294 0.779518 0.836626
Pipeline_7 HPO, FE ExtraTreesClassifier 0.853913 0.777778 0.817000 0.569081 0.702671 0.823529 0.840440 0.72 0.661765 0.839744 0.800000 1.859912 0.776757 0.268382 0.735419 0.839737
Pipeline_8 HPO, FE ExtraTreesClassifier 0.853913 0.777778 0.817000 0.569081 0.702671 0.823529 0.840440 0.72 0.661765 0.839744 0.800000 1.859912 0.776757 0.268382 0.735419 0.839737
Pipeline_3 HPO, FE LGBMClassifier 0.836804 0.875000 0.841346 0.556545 0.558998 0.823529 0.868952 0.80 0.786765 0.839744 0.848485 0.750818 0.798979 0.242647 0.771980 0.853744
Pipeline_1 LGBMClassifier 0.830369 0.812500 0.921218 0.552690 0.546042 0.764706 0.855433 0.72 0.694853 0.794872 0.787879 0.796518 0.763483 0.250000 0.742956 0.823782
Pipeline_2 HPO LGBMClassifier 0.830369 0.812500 0.921218 0.552690 0.546042 0.764706 0.855433 0.72 0.694853 0.794872 0.787879 0.796518 0.763483 0.250000 0.742956 0.823782
Pipeline_5 ExtraTreesClassifier 0.829457 0.789474 0.806148 0.560066 0.586485 0.882353 0.828218 0.76 0.691176 0.833333 0.833333 0.488290 0.763483 0.194853 0.718050 0.830545
Pipeline_6 HPO ExtraTreesClassifier 0.829457 0.789474 0.806148 0.560066 0.586485 0.882353 0.828218 0.76 0.691176 0.833333 0.833333 0.488290 0.763483 0.194853 0.718050 0.830545

You can visualize the scoring metric calculated on a holdout data set.

In [14]:
import pandas as pd
pd.options.plotting.backend = "plotly"

summary.holdout_roc_auc.plot()

Get selected pipeline model¶

Download and reconstruct a scikit-learn pipeline model object from the AutoAI training job.

In [15]:
best_pipeline = pipeline_optimizer.get_pipeline()

Check confusion matrix for selected pipeline.

In [16]:
pipeline_optimizer.get_pipeline_details()['confusion_matrix']
Out[16]:
fn fp tn tp
true_class
Risk 6 2 6 11
No Risk 2 6 11 6

Check features importance for selected pipeline.

In [17]:
pipeline_optimizer.get_pipeline_details()['features_importance']
Out[17]:
features_importance
NewFeature_1_pca_1 1.00
NewFeature_15_round(pca_4) 1.00
NewFeature_11_round(Age) 0.62
NewFeature_0_pca_0 0.56
NewFeature_12_round(pca_0) 0.56
LoanPurpose 0.50
OwnsProperty 0.38
InstallmentPercent 0.38
NewFeature_8_pca_15 0.31
NewFeature_4_pca_4 0.25
LoanAmount 0.25
NewFeature_3_pca_3 0.25
ExistingSavings 0.25
NewFeature_6_pca_9 0.25
NewFeature_5_pca_6 0.19
InstallmentPlans 0.19
NewFeature_9_round(LoanDuration) 0.19
NewFeature_16_round(pca_6) 0.12
CreditHistory 0.12
Age 0.12
ExistingCreditsCount 0.12
OthersOnLoan 0.12
Housing 0.12
NewFeature_18_round(pca_11) 0.12
Telephone 0.06
Sex 0.06
NewFeature_17_round(pca_9) 0.06
Dependents 0.00
NewFeature_7_pca_12 0.00
ForeignWorker 0.00
NewFeature_19_round(pca_12) 0.00
CurrentResidenceDuration 0.00
LoanDuration 0.00
NewFeature_10_round(LoanAmount) 0.00
Job 0.00
NewFeature_2_pca_2 0.00
CheckingStatus 0.00
NewFeature_14_round(pca_2) 0.00
NewFeature_13_round(pca_1) 0.00
EmploymentDuration 0.00

Convert the pipeline model to a Python script and download it¶

In [21]:
from ibm_watson_machine_learning.helpers import pipeline_to_script
pipeline_to_script(best_pipeline)
Out[21]:
Download file.

Visualize pipeline¶

In [18]:
best_pipeline.visualize()
cluster:(root) cluster:tam TAM numpy_column_selector_0 Numpy- Column- Selector compress_strings Compress- Strings numpy_column_selector_0->compress_strings numpy_replace_missing_values_0 Numpy- Replace- Missing- Values compress_strings->numpy_replace_missing_values_0 numpy_replace_unknown_values Numpy- Replace- Unknown- Values numpy_replace_missing_values_0->numpy_replace_unknown_values boolean2float boolean2float numpy_replace_unknown_values->boolean2float cat_imputer Cat- Imputer boolean2float->cat_imputer cat_encoder Cat- Encoder cat_imputer->cat_encoder float32_transform_0 float32_- transform cat_encoder->float32_transform_0 concat_features Concat- Features float32_transform_0->concat_features numpy_column_selector_1 Numpy- Column- Selector float_str2_float Float- Str2- Float numpy_column_selector_1->float_str2_float numpy_replace_missing_values_1 Numpy- Replace- Missing- Values float_str2_float->numpy_replace_missing_values_1 num_imputer Num- Imputer numpy_replace_missing_values_1->num_imputer opt_standard_scaler Opt- Standard- Scaler num_imputer->opt_standard_scaler float32_transform_1 float32_- transform opt_standard_scaler->float32_transform_1 float32_transform_1->concat_features numpy_permute_array Numpy- Permute- Array concat_features->numpy_permute_array pca PCA numpy_permute_array->pca fs1_0 FS1 pca->fs1_0 ta1 TA1 fs1_0->ta1 fs1_1 FS1 ta1->fs1_1 lgbm_classifier LGBM- Classifier fs1_1->lgbm_classifier

Each node in the visualization is a machine-learning operator (transformer or estimator). Each edge indicates data flow (transformed output from one operator becomes input to the next). The input to the root nodes is the initial dataset and the output from the sink node is the final prediction. When you hover the mouse pointer over a node, a tooltip shows you the configuration arguments of the corresponding operator (tuned hyperparameters). When you click on the hyperlink of a node, it brings you to a documentation page for the operator.

Pipeline source code¶

In [ ]:
best_pipeline.pretty_print(ipython_display=True, astype='sklearn')

In the pretty-printed code, >> is the pipe combinator (dataflow edge) and & is the and combinator (combining multiple subpipelines). They correspond to the make_pipeline and make_union functions from scikit-learn, respectively. If you prefer the functions, you can instead pretty-print your pipeline with best_pipeline.pretty_print(ipython_display=True, combinators=False).

Reading training data from COS¶

In [19]:
train_df = pipeline_optimizer.get_data_connections()[0].read()

train_X = train_df.drop(['Risk'], axis=1).values
train_y = train_df.Risk.values

Test pipeline model locally¶

In [20]:
predicted_y = best_pipeline.predict(train_X)
predicted_y[:5]
Out[20]:
array(['No Risk', 'No Risk', 'No Risk', 'No Risk', 'Risk'], dtype=object)

5. Historical runs¶

In this section you learn to work with historical AutoPipelines fit jobs (runs).

To list historical runs use method list().

Note: You can filter runs by providing experiment name.

In [ ]:
experiment.runs(filter='Credit Risk Prediction - AutoAI').list()

To work with historical pipelines found during a particular optimizer run, you need to first provide the run_id to select the fitted optimizer.

Note: you can assign selected run_id to the run_id variable.

In [21]:
run_id = run_details['metadata']['id']

Get executed optimizer's configuration parameters¶

In [22]:
experiment.runs.get_params(run_id=run_id)
Out[22]:
{'name': 'Credit Risk Prediction - AutoAI',
 'desc': '',
 'prediction_type': 'binary',
 'prediction_column': 'Risk',
 'prediction_columns': None,
 'timestamp_column_name': None,
 'holdout_size': 0.1,
 'max_num_daub_ensembles': 2.0,
 't_shirt_size': 'a6c4923b-b8e4-444c-9f43-8a7ec3020110',
 'include_only_estimators': None,
 'cognito_transform_names': None,
 'train_sample_rows_test_size': None,
 'text_processing': None,
 'train_sample_columns_index_list': None,
 'daub_give_priority_to_runtime': None,
 'positive label': None,
 'drop_duplicates': True,
 'csv_separator': ',',
 'excel_sheet': 0,
 'encoding': 'utf-8',
 'retrain_on_holdout': None,
 'scoring': 'roc_auc'}

Get historical optimizer instance and training details¶

In [23]:
historical_opt = experiment.runs.get_optimizer(run_id)
In [24]:
run_details = historical_opt.get_run_details()

List trained pipelines for selected optimizer¶

In [25]:
historical_opt.summary()
Out[25]:
Enhancements Estimator training_roc_auc_(optimized) holdout_precision training_average_precision holdout_average_precision training_log_loss holdout_recall training_precision holdout_accuracy holdout_balanced_accuracy training_recall holdout_f1 holdout_log_loss training_accuracy holdout_roc_auc training_balanced_accuracy training_f1
Pipeline Name
Pipeline_4 HPO, FE LGBMClassifier 0.857847 0.846154 0.847072 0.547020 0.565612 0.647059 0.885287 0.68 0.698529 0.794872 0.733333 0.599960 0.785886 0.235294 0.779518 0.836626
Pipeline_7 HPO, FE ExtraTreesClassifier 0.853913 0.777778 0.817000 0.569081 0.702671 0.823529 0.840440 0.72 0.661765 0.839744 0.800000 1.859912 0.776757 0.268382 0.735419 0.839737
Pipeline_8 HPO, FE ExtraTreesClassifier 0.853913 0.777778 0.817000 0.569081 0.702671 0.823529 0.840440 0.72 0.661765 0.839744 0.800000 1.859912 0.776757 0.268382 0.735419 0.839737
Pipeline_3 HPO, FE LGBMClassifier 0.836804 0.875000 0.841346 0.556545 0.558998 0.823529 0.868952 0.80 0.786765 0.839744 0.848485 0.750818 0.798979 0.242647 0.771980 0.853744
Pipeline_1 LGBMClassifier 0.830369 0.812500 0.921218 0.552690 0.546042 0.764706 0.855433 0.72 0.694853 0.794872 0.787879 0.796518 0.763483 0.250000 0.742956 0.823782
Pipeline_2 HPO LGBMClassifier 0.830369 0.812500 0.921218 0.552690 0.546042 0.764706 0.855433 0.72 0.694853 0.794872 0.787879 0.796518 0.763483 0.250000 0.742956 0.823782
Pipeline_5 ExtraTreesClassifier 0.829457 0.789474 0.806148 0.560066 0.586485 0.882353 0.828218 0.76 0.691176 0.833333 0.833333 0.488290 0.763483 0.194853 0.718050 0.830545
Pipeline_6 HPO ExtraTreesClassifier 0.829457 0.789474 0.806148 0.560066 0.586485 0.882353 0.828218 0.76 0.691176 0.833333 0.833333 0.488290 0.763483 0.194853 0.718050 0.830545

Get selected pipeline and test locally¶

In [26]:
hist_pipeline = historical_opt.get_pipeline(pipeline_name='Pipeline_3')
In [27]:
predicted_y = hist_pipeline.predict(train_X)
predicted_y[:5]
Out[27]:
array(['No Risk', 'No Risk', 'No Risk', 'No Risk', 'Risk'], dtype=object)

6. Pipeline refinement with Lale and testing¶

In this section you learn how to refine and retrain the best pipeline returned by AutoAI. There are many ways to refine a pipeline. For illustration, simply replace the final estimator in the pipeline by an interpretable model. The call to wrap_imported_operators() augments scikit-learn operators with schemas for hyperparameter tuning.

In [28]:
from sklearn.linear_model import LogisticRegression as LR
from sklearn.tree import DecisionTreeClassifier as Tree
from sklearn.neighbors import KNeighborsClassifier as KNN
from lale.lib.lale import Hyperopt
from lale import wrap_imported_operators

wrap_imported_operators()

Pipeline decomposition and new definition¶

Start by removing the last step of the pipeline, i.e., the final estimator.

In [29]:
prefix = hist_pipeline.remove_last().freeze_trainable()
prefix.visualize()
cluster:(root) cluster:tam TAM numpy_column_selector_0 Numpy- Column- Selector compress_strings Compress- Strings numpy_column_selector_0->compress_strings numpy_replace_missing_values_0 Numpy- Replace- Missing- Values compress_strings->numpy_replace_missing_values_0 numpy_replace_unknown_values Numpy- Replace- Unknown- Values numpy_replace_missing_values_0->numpy_replace_unknown_values boolean2float boolean2float numpy_replace_unknown_values->boolean2float cat_imputer Cat- Imputer boolean2float->cat_imputer cat_encoder Cat- Encoder cat_imputer->cat_encoder float32_transform_0 float32_- transform cat_encoder->float32_transform_0 concat_features Concat- Features float32_transform_0->concat_features numpy_column_selector_1 Numpy- Column- Selector float_str2_float Float- Str2- Float numpy_column_selector_1->float_str2_float numpy_replace_missing_values_1 Numpy- Replace- Missing- Values float_str2_float->numpy_replace_missing_values_1 num_imputer Num- Imputer numpy_replace_missing_values_1->num_imputer opt_standard_scaler Opt- Standard- Scaler num_imputer->opt_standard_scaler float32_transform_1 float32_- transform opt_standard_scaler->float32_transform_1 float32_transform_1->concat_features numpy_permute_array Numpy- Permute- Array concat_features->numpy_permute_array pca PCA numpy_permute_array->pca fs1_0 FS1 pca->fs1_0 ta1 TA1 fs1_0->ta1 fs1_1 FS1 ta1->fs1_1

Next, add a new final step, which consists of a choice of three estimators. In this code, | is the or combinator (algorithmic choice). It defines a search space for another optimizer run.

In [30]:
new_pipeline = prefix >> (LR | Tree | KNN)
new_pipeline.visualize()
cluster:(root) cluster:tam TAM cluster:choice Choice numpy_column_selector_0 Numpy- Column- Selector compress_strings Compress- Strings numpy_column_selector_0->compress_strings numpy_replace_missing_values_0 Numpy- Replace- Missing- Values compress_strings->numpy_replace_missing_values_0 numpy_replace_unknown_values Numpy- Replace- Unknown- Values numpy_replace_missing_values_0->numpy_replace_unknown_values boolean2float boolean2float numpy_replace_unknown_values->boolean2float cat_imputer Cat- Imputer boolean2float->cat_imputer cat_encoder Cat- Encoder cat_imputer->cat_encoder float32_transform_0 float32_- transform cat_encoder->float32_transform_0 concat_features Concat- Features float32_transform_0->concat_features numpy_column_selector_1 Numpy- Column- Selector float_str2_float Float- Str2- Float numpy_column_selector_1->float_str2_float numpy_replace_missing_values_1 Numpy- Replace- Missing- Values float_str2_float->numpy_replace_missing_values_1 num_imputer Num- Imputer numpy_replace_missing_values_1->num_imputer opt_standard_scaler Opt- Standard- Scaler num_imputer->opt_standard_scaler float32_transform_1 float32_- transform opt_standard_scaler->float32_transform_1 float32_transform_1->concat_features numpy_permute_array Numpy- Permute- Array concat_features->numpy_permute_array pca PCA numpy_permute_array->pca fs1_0 FS1 pca->fs1_0 ta1 TA1 fs1_0->ta1 fs1_1 FS1 ta1->fs1_1 lr LR fs1_1->lr tree Tree knn KNN

New optimizer Hyperopt configuration and training¶

To automatically select the algorithm and tune its hyperparameters, we create an instance of the Hyperopt optimizer and fit it to the data.

In [31]:
from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(train_X, train_y, test_size=0.15, random_state=33)
In [32]:
hyperopt = Hyperopt(estimator=new_pipeline, cv=3, max_evals=20, scoring='roc_auc')
hyperopt_pipelines = hyperopt.fit(X_train, y_train)
The enumeration ['PCA'] is all lale operators, but the schema fragment {'enum': [PCA()]} it is part of does not stipulate that it should be 'laleType':'operator'.  While legal, this likely indicates either an omission in the schema or a bug in the schema simplifier
The enumeration ['PCA'] is all lale operators, but the schema fragment {'enum': [PCA()]} it is part of does not stipulate that it should be 'laleType':'operator'.  While legal, this likely indicates either an omission in the schema or a bug in the schema simplifier
100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 20/20 [00:45<00:00,  2.25s/trial, best loss: -0.8305747694334652]
In [33]:
pipeline_model = hyperopt_pipelines.get_pipeline()

Pipeline model tests and visualization¶

In [34]:
from sklearn.metrics import roc_auc_score

predicted_y = pipeline_model.predict(X_test)
score = roc_auc_score(predicted_y=='Risk', y_test=='Risk')
print(f'roc_auc_score {score:.1%}')
roc_auc_score 79.3%
In [35]:
pipeline_model.visualize()
cluster:(root) cluster:tam TAM numpy_column_selector_0 Numpy- Column- Selector compress_strings Compress- Strings numpy_column_selector_0->compress_strings numpy_replace_missing_values_0 Numpy- Replace- Missing- Values compress_strings->numpy_replace_missing_values_0 numpy_replace_unknown_values Numpy- Replace- Unknown- Values numpy_replace_missing_values_0->numpy_replace_unknown_values boolean2float boolean2float numpy_replace_unknown_values->boolean2float cat_imputer Cat- Imputer boolean2float->cat_imputer cat_encoder Cat- Encoder cat_imputer->cat_encoder float32_transform_0 float32_- transform cat_encoder->float32_transform_0 concat_features Concat- Features float32_transform_0->concat_features numpy_column_selector_1 Numpy- Column- Selector float_str2_float Float- Str2- Float numpy_column_selector_1->float_str2_float numpy_replace_missing_values_1 Numpy- Replace- Missing- Values float_str2_float->numpy_replace_missing_values_1 num_imputer Num- Imputer numpy_replace_missing_values_1->num_imputer opt_standard_scaler Opt- Standard- Scaler num_imputer->opt_standard_scaler float32_transform_1 float32_- transform opt_standard_scaler->float32_transform_1 float32_transform_1->concat_features numpy_permute_array Numpy- Permute- Array concat_features->numpy_permute_array pca PCA numpy_permute_array->pca fs1_0 FS1 pca->fs1_0 ta1 TA1 fs1_0->ta1 fs1_1 FS1 ta1->fs1_1 lr LR fs1_1->lr

7. Deploy and Score¶

In this section you will learn how to deploy and score pipeline model as webservice using WML instance.

In [36]:
pipeline_name = "Pipeline_1"

Online deployment creation¶

In [37]:
from ibm_watson_machine_learning.deployment import WebService

service = WebService(wml_credentials, source_space_id=space_id)

service.create(
    experiment_run_id=run_id,
    model=pipeline_name, 
    deployment_name="Credit Risk Deployment AutoAI")
Preparing an AutoAI Deployment...
Published model uid: 50027806-e9a5-462a-8389-87446e7d8dee
Deploying model 50027806-e9a5-462a-8389-87446e7d8dee using V4 client.


#######################################################################################

Synchronous deployment creation for uid: '50027806-e9a5-462a-8389-87446e7d8dee' started

#######################################################################################


initializing
Note: online_url is deprecated and will be removed in a future release. Use serving_urls instead.
...
ready


------------------------------------------------------------------------------------------------
Successfully finished deployment creation, deployment_uid='2d936eb1-34e7-439c-8ff5-79057a90c71f'
------------------------------------------------------------------------------------------------


Deployment object could be printed to show basic information:

In [38]:
print(service)
name: Credit Risk Deployment AutoAI, id: 2d936eb1-34e7-439c-8ff5-79057a90c71f, scoring_url: https://yp-qa.ml.cloud.ibm.com/ml/v4/deployments/2d936eb1-34e7-439c-8ff5-79057a90c71f/predictions, asset_id: 50027806-e9a5-462a-8389-87446e7d8dee

To show all available information about the deployment use the .get_params() method:

In [39]:
service.get_params()
Note: online_url is deprecated and will be removed in a future release. Use serving_urls instead.
Out[39]:
{'entity': {'asset': {'id': '50027806-e9a5-462a-8389-87446e7d8dee'},
  'custom': {},
  'deployed_asset_type': 'model',
  'hybrid_pipeline_hardware_specs': [{'hardware_spec': {'name': 'S',
     'num_nodes': 1},
    'node_runtime_id': 'auto_ai.kb'}],
  'name': 'Credit Risk Deployment AutoAI',
  'online': {},
  'space_id': '680a7515-620c-461f-9c6f-1f4c535bfc47',
  'status': {'online_url': {'url': 'https://yp-qa.ml.cloud.ibm.com/ml/v4/deployments/2d936eb1-34e7-439c-8ff5-79057a90c71f/predictions'},
   'serving_urls': ['https://yp-qa.ml.cloud.ibm.com/ml/v4/deployments/2d936eb1-34e7-439c-8ff5-79057a90c71f/predictions'],
   'state': 'ready'}},
 'metadata': {'created_at': '2022-04-12T10:48:44.514Z',
  'id': '2d936eb1-34e7-439c-8ff5-79057a90c71f',
  'modified_at': '2022-04-12T10:48:44.514Z',
  'name': 'Credit Risk Deployment AutoAI',
  'owner': 'IBMid-55000091VC',
  'space_id': '680a7515-620c-461f-9c6f-1f4c535bfc47'},
 'system': {'warnings': [{'id': 'Deprecated',
    'message': 'online_url is deprecated and will be removed in a future release. Use serving_urls instead.'}]}}

Scoring of webservice¶

You can make scoring request by calling score() on deployed pipeline.

In [40]:
predictions = service.score(payload=train_df.drop(['Risk'], axis=1).iloc[:10])
predictions
Out[40]:
{'predictions': [{'fields': ['prediction', 'probability'],
   'values': [['No Risk', [0.974324555367238, 0.025675444632761894]],
    ['No Risk', [0.9964006989119355, 0.0035993010880644594]],
    ['No Risk', [0.9656931624922778, 0.03430683750772225]],
    ['No Risk', [0.9134356070206268, 0.08656439297937323]],
    ['Risk', [0.02306423364828436, 0.9769357663517156]],
    ['Risk', [0.0369640085999573, 0.9630359914000427]],
    ['No Risk', [0.9703778439759995, 0.02962215602400054]],
    ['No Risk', [0.9442598047315383, 0.055740195268461766]],
    ['No Risk', [0.9955439396853191, 0.004456060314680909]],
    ['Risk', [0.006516138445265551, 0.9934838615547344]]]}]}

If you want to work with the web service in an external Python application you can retrieve the service object by:

  • Initialize the service by service = WebService(wml_credentials)
  • Get deployment_id by service.list() method
  • Get webservice object by service.get('deployment_id') method

After that you can call service.score() method.

Deleting deployment¶

You can delete the existing deployment by calling the service.delete() command. To list the existing web services you can use service.list().

Batch deployment creation¶

A batch deployment processes input data from a inline data and return predictions in scoring details.

In [41]:
batch_payload_df = train_df.drop(['Risk'], axis=1)[:5]
batch_payload_df
Out[41]:
CheckingStatus LoanDuration CreditHistory LoanPurpose LoanAmount ExistingSavings EmploymentDuration InstallmentPercent Sex OthersOnLoan CurrentResidenceDuration OwnsProperty Age InstallmentPlans Housing ExistingCreditsCount Job Dependents Telephone ForeignWorker
0 0_to_200 31 credits_paid_to_date other 1889 100_to_500 less_1 3 female none 3 savings_insurance 32 none own 1 skilled 1 none yes
1 less_0 18 credits_paid_to_date car_new 462 less_100 1_to_4 2 female none 2 savings_insurance 37 stores own 2 skilled 1 none yes
2 less_0 15 prior_payments_delayed furniture 250 less_100 1_to_4 2 male none 3 real_estate 28 none own 2 skilled 1 yes no
3 0_to_200 28 credits_paid_to_date retraining 3693 less_100 greater_7 3 male none 2 savings_insurance 32 none own 1 skilled 1 none yes
4 no_checking 28 prior_payments_delayed education 6235 500_to_1000 greater_7 3 male none 3 unknown 57 none own 2 skilled 1 none yes

Create batch deployment for Pipeline_2 created in AutoAI experiment with the run_id.

In [42]:
from ibm_watson_machine_learning.deployment import Batch

service_batch = Batch(wml_credentials,source_space_id=space_id)
service_batch.create(
            experiment_run_id=run_id,
            model="Pipeline_2",
            deployment_name="Credit Risk Batch Deployment AutoAI")
Preparing an AutoAI Deployment...
Published model uid: 160858bf-1737-4fcf-956c-188e9437156f
Deploying model 160858bf-1737-4fcf-956c-188e9437156f using V4 client.


#######################################################################################

Synchronous deployment creation for uid: '160858bf-1737-4fcf-956c-188e9437156f' started

#######################################################################################


ready.


------------------------------------------------------------------------------------------------
Successfully finished deployment creation, deployment_uid='f529ae97-50d7-4d8d-b085-f273589d5af5'
------------------------------------------------------------------------------------------------


Score batch deployment with inline payload as pandas DataFrame.¶

In [43]:
scoring_params = service_batch.run_job(
            payload=batch_payload_df,
            background_mode=False)

##########################################################################

Synchronous scoring for id: '75c917f1-6483-48fd-aed7-332b06daeb7c' started

##########################################################################


queued..
running
completed
Scoring job  '75c917f1-6483-48fd-aed7-332b06daeb7c' finished successfully.
In [44]:
scoring_params['entity']['scoring'].get('predictions')
Out[44]:
[{'fields': ['prediction', 'probability'],
  'values': [['No Risk', [0.974324555367238, 0.025675444632761894]],
   ['No Risk', [0.9964006989119355, 0.0035993010880644594]],
   ['No Risk', [0.9656931624922778, 0.03430683750772225]],
   ['No Risk', [0.9134356070206268, 0.08656439297937323]],
   ['Risk', [0.02306423364828436, 0.9769357663517156]]]}]

8. Clean up¶

If you want to clean up all created assets:

  • experiments
  • trainings
  • pipelines
  • model definitions
  • models
  • functions
  • deployments

please follow up this sample notebook.

9. Summary and next steps¶

You successfully completed this notebook!.

You learned how to use ibm-watson-machine-learning to run AutoAI experiments.

Check out our Online Documentation for more samples, tutorials, documentation, how-tos, and blog posts.

Authors¶

Lukasz Cmielowski, PhD, is an Automation Architect and Data Scientist at IBM with a track record of developing enterprise-level applications that substantially increases clients' ability to turn data into actionable knowledge.

Amadeusz Masny, Python Software Developer in Watson Machine Learning at IBM

Kiran Kate, Senior Software Engineer at IBM Research AI

Martin Hirzel, Research Staff Member and Manager at IBM Research AI

Jan Sołtysik, Intern in Watson Machine Learning

Copyright © 2020, 2021, 2022 IBM. This notebook and its source code are released under the terms of the MIT License.